package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.ui.AbstractSpinerAdapter.IOnItemSelectListener;
import com.longrise.bjjt.util.UiUtil;

import java.util.ArrayList;
import java.util.List;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.UiUtils;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;

/**
 * 事故上传的信息填写界面，Created by Administrator on 2016/5/12.
 */
public class SingleAccidentLoadingView extends LFView implements View.OnClickListener, IOnItemSelectListener, ILSMsgListener
        , ILFMsgListener {
    private String appCaseNo;//案件编号
    private Context context = null;
    private View view = null;
    private BaseApplication mApplication;
    private Dialog processDialog;
    private EntityBean[] DrivingLicenceBeans;//车辆信息
    private EntityBean myDrivingLiscenceBean;//驾驶证的bean
    private List<String> carnoList = null;
    private LinearLayout hn_btn_back;
    private TextView tv_title;
    private Button bt_singleaccidentloading;
    private Button bt_singleaccidentloading_record;
    private EditText et_singleaccidentloadingpic5;
    private EditText et_singleaccdentidcardme;
    private RelativeLayout rl_singlesingleaccidentloading;
    private TextView et_singleaccidentloadingpic4;
    private String myCarType;
    private String myCarFrameNo;
    private String myCarPic;
    private EditText phoneET;
    private EditText myInsnoET;//己方保单号
    private TextView myGetTV;//获取己方保单号
    private Dialog cpsDialog;


    public SingleAccidentLoadingView(Context context, String appCaseNo, EntityBean myDrivingLiscenceBean) {
        super(context);
        this.context = context;
        this.appCaseNo = appCaseNo;
        this.mApplication = ((MainActivity) context).getAppData();
        this.myDrivingLiscenceBean = myDrivingLiscenceBean;

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {
        checkBindingCarInfo();
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        initData();
    }

    //查询
    private void initData() {
        carnoList = new ArrayList<String>();

        ((MainActivity) context).initHelpView(view, appCaseNo);
    }


    private void initView() {
        view = View.inflate(context, R.layout.view_accidentloadingsingle, null);
        bt_singleaccidentloading = (Button) view.findViewById(R.id.bt_singleaccidentloading);
        bt_singleaccidentloading_record = (Button) view.findViewById(R.id.bt_singleaccidentloading_record);
        et_singleaccidentloadingpic5 = (EditText) view.findViewById(R.id.et_singleaccidentloadingpic5);
        et_singleaccidentloadingpic4 = (TextView) view.findViewById(R.id.et_singleaccidentloadingpic4);
        et_singleaccdentidcardme = (EditText) view.findViewById(R.id.et_singleaccdentidcardme);//本方驾驶证号
        et_singleaccdentidcardme.setText(myDrivingLiscenceBean.getString("cardno"));
        et_singleaccidentloadingpic5.setText(myDrivingLiscenceBean.getString("carownername"));
        rl_singlesingleaccidentloading = (RelativeLayout) view.findViewById(R.id.rl_singlesingleaccidentloading);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("事故上传");

        phoneET = (EditText) view.findViewById(R.id.et_singleaccdentidcardmetel);
        phoneET.setText(mApplication.getLoginInfo().getBean("userinfo").getString("mobilephone"));

        myInsnoET = (EditText) view.findViewById(R.id.et_singleaccdentcpsno);
        myGetTV = (TextView) view.findViewById(R.id.singleaload_tv_myget);

        //统计区分
        String text = context.getResources().getString(R.string.accident_commit_single);
        bt_singleaccidentloading.setText(CommontUtils.changeStrColor(text, "提交", Color.WHITE));
    }

    private void regEvent(boolean b) {
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (null != bt_singleaccidentloading) {
            bt_singleaccidentloading.setOnClickListener(b ? this : null);
        }
        if (null != bt_singleaccidentloading_record) {
            bt_singleaccidentloading_record.setOnClickListener(b ? this : null);
        }
        if (null != rl_singlesingleaccidentloading) {
            rl_singlesingleaccidentloading.setOnClickListener(b ? this : null);
        }
        if (null != myGetTV) {
            myGetTV.setOnClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
            this.addILFMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
            this.removeILFMsgListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hn_btn_back:
                OnDestroy();
                closeForm();
                break;
            case R.id.bt_singleaccidentloading_record:
                BindCarView bindcarview = new BindCarView(context, null);
                FrameworkManager.getInstance().showNewForm(context, bindcarview);
                break;
            case R.id.rl_singlesingleaccidentloading:
                UiUtil.showSelectPopWindow(context, carnoList, this, rl_singlesingleaccidentloading, true);
                break;
            case R.id.bt_singleaccidentloading: //提交
                submitAccidentCase();
                break;
            case R.id.singleaload_tv_myget://获取本方保单
                String myCarNo = et_singleaccidentloadingpic4.getText().toString().trim();//车牌号
                if (TextUtils.isEmpty(myCarNo)) {
                    UiUtil.showToast(context, "请选择车牌号");
                    return;
                }
                String myframeno = getCarTypeCode(myCarNo).get(1);
                getCpsno(myCarNo, myframeno);
                myInsnoET.setText("");//重置保单号
                break;
        }
    }

    //获取保单号
    private void getCpsno(String carno, String frameno) {
        String uid = mApplication.getKckpName();
        String token = mApplication.getToken();
//        DialogUtils.showDialog(context);
        if (null == cpsDialog) {
            cpsDialog = UiUtil.showProcessDialog(context, "查询承保信息中");
        } else {
            cpsDialog.show();
        }
        ApiImpI.getInstance(context).searchCpsNum(uid, token, carno, frameno, appCaseNo, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
//                DialogUtils.closeDialog();
                if (null != cpsDialog && cpsDialog.isShowing()) {
                    cpsDialog.dismiss();
                }
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(context, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
//                DialogUtils.closeDialog();
                if (null != cpsDialog && cpsDialog.isShowing()) {
                    cpsDialog.dismiss();
                }
                if (null == view) {
                    return;
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    EntityBean dataBean = bean.getBean("data");
                    String isValid = dataBean.getString("isVaild");
                    if (TextUtils.equals(isValid, "0")) {
                        String insno = dataBean.getString("trafficinsno");
                        myInsnoET.setText(insno);
                    }
                } else {
                    String error = bean.getString("redes");
                    if (!TextUtils.isEmpty(error)) {
                        UiUtil.showToast(context, error);
                    }
                }
            }
        });
    }

    @Override
    public void onItemClick(int pos, View view) {
        switch (view.getId()) {
            case R.id.rl_singlesingleaccidentloading:
                String current = et_singleaccidentloadingpic4.getText().toString().trim();
                String select = carnoList.get(pos);
                if (TextUtils.equals(current, select)) {//选择的同一个
                    return;
                }
                et_singleaccidentloadingpic4.setText(carnoList.get(pos));
                //cartypeString = carTypeList.get(pos);
                myInsnoET.setText("");
                break;
            default:
                break;
        }
    }


    //根据用户id查询用户绑定的车辆信息
    private void checkBindingCarInfo() {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        EntityBean userInfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("uid", userInfo.get("id"));
        bean.set("token", mApplication.getToken());

        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.KCKPSEARCHCARS, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (null == view) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            DrivingLicenceBeans = bean.getBeans("data");
                            if (null != DrivingLicenceBeans && DrivingLicenceBeans.length > 0) {
                                carnoList.clear();
                                for (EntityBean eBean : DrivingLicenceBeans) {
                                    carnoList.add(eBean
                                            .getString("carno"));
                                }
                            }
                        }
//                        else {
//                            UiUtil.showToast(context, redes);
//                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    @Override
    public Object onLSMsg(int arg0, Object... arg1) {
        if (arg0 == 99) {
            //绑定成功调取查询车辆
            checkBindingCarInfo();
        }
        return null;
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {//点击返回按键
            OnDestroy();
            closeForm();
        }
        return null;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        DrivingLicenceBeans = null;
        if (null != carnoList) {
            carnoList.clear();
            carnoList = null;
        }
        if (null != processDialog) {
            processDialog.dismiss();
            processDialog = null;
        }
        if (null != cpsDialog) {
            cpsDialog.dismiss();
            cpsDialog = null;
        }
        regEvent(false);
    }

    //事故上传
    private void submitAccidentCase() {
        String myCarNo = et_singleaccidentloadingpic4.getText().toString().trim();//车牌号
        if (TextUtils.isEmpty(myCarNo)) {
            UiUtil.showToast(context, "请选择车牌号");
            return;
        }
        String phoneNumber = phoneET.getText().toString().trim();//手机号
        if (TextUtils.isEmpty(phoneNumber)) {
            UiUtil.showToast(context, "请输入正确的手机号");
            return;
        }
        String insno = myInsnoET.getText().toString().trim();//保单号
//        if (TextUtils.isEmpty(insno)) {
//            UiUtil.showToast(context, "请获取保单号");
//            return;
//        }
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        bean.set("username", mApplication.getLoginInfo().getBean("userinfo").getString("userflag"));
        // caseno
        bean.set("appcaseno", appCaseNo);
        bean.set("casecarno", myCarNo);
        bean.set("appphone", phoneNumber);
        // 经度
        bean.set("caselon", mApplication.getLongitude());
        // 纬度
        bean.set("caselat", mApplication.getLatitude());
        // 地址
        bean.set("accidentplace", mApplication.getAddress());
        // 提交时间
        bean.set("sibmitdate", CommontUtils.getNowTime());
        //bean.set("areaid", userinfo.getString("areaid")); // 区域
        bean.set("areaid", mApplication.getAreaid()); // 调试数据
        bean.set("alarmtime", CommontUtils.getNowTime());
        bean.set("uid", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        bean.set("accidenttype", "");
        bean.set("accidentdes", "");
        bean.set("disposetype", "1");//增加一个自己还是交警定责的类型字段
        List<String> carTypeCode = getCarTypeCode(myCarNo);
        if (null != carTypeCode) {
            myCarType = carTypeCode.get(0);
            myCarFrameNo = carTypeCode.get(1);
            myCarPic = carTypeCode.get(2);
        }
        final EntityBean[] casecarlist = new EntityBean[1];//车主信息数组
        EntityBean bfBean = new EntityBean();// 本方数据
        String myName = et_singleaccidentloadingpic5.getText().toString().trim(); // 车主姓名
        bfBean.set("carownname", myName);
        bfBean.set("carownphone", phoneNumber); //手机号
        bfBean.set("driverlicence", et_singleaccdentidcardme.getText().toString().trim()); //
        bfBean.set("casecarno", et_singleaccidentloadingpic4.getText().toString().trim()); // 案件车牌号
        bfBean.set("cartype", myCarType); // 车型
        bfBean.set("frameno", myCarFrameNo);//车架号
        bfBean.set("cardno", et_singleaccdentidcardme.getText().toString().trim()); //身份证
        bfBean.set("driverfileno", myDrivingLiscenceBean.getString("driverfileno")); //档案编号
        bfBean.set("drivernoimg", myDrivingLiscenceBean.getString("drivernoimg")); //驾驶证照片
        bfBean.set("drivingnoimg", myCarPic);  //行驶证照片
        bfBean.set("dutytype", "0");  //单车默认全责
        bfBean.set("trafficinsno", insno);  //保单号
        bfBean.set("party", "1");  //己方
        casecarlist[0] = bfBean;

        bean.set("casecarlist", casecarlist);
        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.SUBMITCASEINFOR, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (null == view) {
                            return;
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            UiUtil.showToast(context, "提交成功");
                            //单车提交后直接进入保险报案
                            InsuranceReportChoiceView iView = new InsuranceReportChoiceView(context, casecarlist, appCaseNo);
                            iView.setIfSingle("0");
                            FrameworkManager.getInstance().showNewForm(context, iView);
                        } else if (TextUtils.equals(restate, "-19")) {//交强险验证失败
                            UiUtils.showSingleDialog(context, R.mipmap.warn, redes, "确认",
                                    new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            return;
                                        }
                                    });
                        } else {
                            UiUtil.showToast(context, redes);
                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                        return;
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    /**
     * 根据车牌获取获取车型，车架号，行驶证照片
     *
     * @param carNo
     * @return
     */
    private List<String> getCarTypeCode(String carNo) {
        if (TextUtils.isEmpty(carNo)) {
            return null;
        }
        List<String> myCarInfo = new ArrayList<String>();
        String value1 = "";
        String value2 = "";
        String value3 = "";
        for (EntityBean bean : DrivingLicenceBeans) {
            String getCarInfo = bean.getString("carno");
            if (carNo.equals(getCarInfo)) {
                value1 = bean.getString("cartype");//车型
                myCarInfo.add(value1);
                value2 = bean.getString("identificationnum");//车架号
                myCarInfo.add(value2);
                value3 = bean.getString("drivingnoimg");//行驶证照片
                myCarInfo.add(value3);
                break;
            }
        }
        return myCarInfo;
    }
}
